package de.dailab.prefgen;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import de.dailab.prefgen.INameMapping.TYPE;
import de.dailab.prefgen.ObjectAnnotations.ValueLimitations;


import android.preference.Preference;
import android.preference.PreferenceActivity;

public class SeekBarIntegerLeaf implements ILeafFactory {

	@Override
	public Preference generate(Object superObject, Method callingMethod,
			PreferenceActivity context, INameMapping nameMapping) {

		SeekBarPreference seekbar = new SeekBarPreference(context);
		seekbar.setKey(nameMapping.toHumanReadable(callingMethod,superObject, TYPE.KEY));
		seekbar
				.setTitle(nameMapping
						.toHumanReadable(callingMethod, superObject,TYPE.TITLE));
		seekbar.setSummary(nameMapping.toHumanReadable(callingMethod,superObject,
				TYPE.DESCRIPTION));
		
		seekbar.setOnPreferenceChangeListener(new OnLeafPrefernceChangedListener(
				superObject, callingMethod, nameMapping));
		
		seekbar.setPersistent(false);

		Integer obj;

		Annotation[] declaredAnnotations = callingMethod
				.getDeclaredAnnotations();

		for (Annotation a : declaredAnnotations) {
			System.out.println(a);
		}

		try {
			obj = (Integer) callingMethod.invoke(superObject, null);

			if (obj != null) {
				seekbar.setOldValue(obj);
				ValueLimitations annotation = callingMethod
						.getAnnotation(ObjectAnnotations.ValueLimitations.class);
				if (annotation != null) {
					seekbar.setMaximum(annotation.max());
					seekbar.setMinimum(annotation.min());
					// TODO change minimum
					// seekbar.minimum = annotation.min();
				}

			}
			

			return seekbar;

		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}

	@Override
	public boolean shouldGenerate(Class type) {
		// TODO Auto-generated method stub
		return Integer.class.isAssignableFrom(type)
				|| (type.isPrimitive() && type.getName().equals("int"));
		// && type
		// .isAnnotationPresent(ObjectAnnotations.ValueLimitations.class);
	}

}
